package com.myframework.utils.stringutil;

import java.util.StringTokenizer;

public class StringUtil {

	/**
	 * Returns true if the given string is either null or an empty string after
	 * the white space is trimmed off of both ends.
	 * 
	 * @param str
	 *          The String to check
	 * @return 'true' if the given string trimmed is empty (or null), 'false'
	 *         otherwise
	 */
	public static boolean isEmpty(final String str) {
		if (null == str) {
			return true;
		}

		if ("".equals(str.trim())) {
			return true;
		}

		return false;
	}

	/**
	 * Splits the input string by characters in the given delimiter into an array
	 * of strings. If the input string is null, null will be returned. If a
	 * multi-character string is passed as the delimiter, each character in the
	 * string will be used as a delimiter. The String passed in as the delimiter
	 * is <i>not</i> used as a multi-character delimiter.
	 * 
	 * @param str
	 *          The string to be split
	 * @param delim
	 *          The String of delimiting characters to use
	 * @return An array of string split or null
	 */
	public static String[] split(final String str, final String delim) {
		String[] splitStr = null;

		if (str != null && delim != null) {
			StringTokenizer tokenizer = new StringTokenizer(str, delim);
			splitStr = new String[tokenizer.countTokens()];
			for (int i = 0; i < splitStr.length; i++) {
				splitStr[i] = tokenizer.nextToken();
			}
		}

		return splitStr;
	}

	/**
	 * Works like Oracle NVL function. This will return empty string if all values
	 * are empty or null.
	 * 
	 * @param values
	 * @return
	 */
	public static String defaultIfEmpty(final String... values) {
		for (String value : values) {
			if (!StringUtil.isEmpty(value)) {
				return value;
			}
		}
		return "";
	}

}
